package com.wyc.internalCommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wyc.internalCommon.result.TokenResult;

import java.util.Calendar;
import java.util.HashMap;


public class JWTUtils {

    private static final String SIGN = "SVHerd$#@^^";

    // 手机号
    private static final String JWT_KEY_PHONE = "phone";

    // 身份标识 乘客：1    2：司机
    private static final String JWT_KEY_IDENTITY = "identity";

    // 双token类型 successToken/refreshToken
    private static final String JWT_TOKEN_TYPE = "tokenType";

    // 防止token重复
    private static final String JWT_TOKEN_DATE = "tokenTime";

    /**
     * 生成token
     * @param phone
     * @param identity
     * @return
     */
    public static String generatorToken(String phone,String identity,String tokenType){
        HashMap<String, String> map = new HashMap<>();
        map.put(JWT_KEY_PHONE,phone);
        map.put(JWT_KEY_IDENTITY,identity);
        map.put(JWT_TOKEN_TYPE,tokenType);
        // token过期时间
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE,1);
//        Date date = calendar.getTime();
        map.put(JWT_TOKEN_DATE,Calendar.getInstance().getTime().toString());

        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        // 整合过期时间
//        builder.withExpiresAt(date);

        // 生成token
        String sign = builder.sign(Algorithm.HMAC384(SIGN));

        return sign;
    }

    /**
     * JWT解码
     * @param token
     * @return
     */
    public static TokenResult parseJWT(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC384(SIGN)).build().verify(token);
        // toString 会在前后加“” , 而verify本身自带“”，所以使用asString
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static TokenResult checkToken(String token){
        TokenResult tokenResult = null;
        try {
            tokenResult = JWTUtils.parseJWT(token);
        }catch (Exception e){

        }
        return tokenResult;
    }

}
